import React, {useState} from 'react';
import {Text, View, StyleSheet} from 'react-native';
import {Button, Modal, Toast, Flex} from '@ant-design/react-native';
import {ScrollView} from 'react-native-gesture-handler';
import {IconX} from '@/rcomponents/iconx';
import MovementStore from './movementStore';
import RackMaterialStore from './components/rackMaterialStore';
import ScannedMaterialCard from './components/scannedMaterialCard';
import RackMaterialScanner from './components/rackMaterialScanner';

const styles = StyleSheet.create({
  centerScrollContainer: {
    flexGrow: 1,
    justifyContent: 'center',
  },
  emptyMoveContainer: {
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: 'transparent',
  },
  hpadding5: {
    paddingHorizontal: 5,
  },
  scanFlex: {
    flex: 1,
  },
  moveActionFlex: {
    flex: 2,
    paddingLeft: 5,
  },
});

function AerialMaterialMovement({navigation}) {
  const moveStore = MovementStore.useStore();
  const rackmatStore = RackMaterialStore.useStore();
  const [scanning, setScanning] = useState(false);
  const {movingParts} = moveStore;
  const isMovingEmpty = movingParts.length === 0;
  const handleMaterialScan = async (rack, materialBarcode) => {
    const materialRes = await moveStore.getMaterialByRackAndPart(
      rack.tid,
      rack.shelfName,
      materialBarcode,
    );
    if (materialRes.errorCode) {
      Toast.fail('扫码获取料件信息失败,请重试');
    } else {
      const resData = materialRes.data;
      const thisPart = {
        id: resData.amPartId,
        serial_no: resData.apSn,
        part_no: resData.apPn,
        barcode: resData.apCode,
        batch_no: resData.apSysBatchNo,
        stock_qty: resData.stockNum,
        rack_no: resData.asdSubName,
        rack_shelf_id: resData.shelfLatticeId,
        name: resData.apName,
        qty: 1,
      };
      const existPart = movingParts.find(
        (shp) =>
          shp.batch_no === thisPart.batch_no &&
          shp.rack_no === thisPart.rack_no,
      );
      if (existPart) {
        Toast.fail('此料件已选择，请勿重复选择');
        return;
      }
      if (!thisPart.serial_no) {
        let partQtyModalInfo = {
          visible: true,
          qty: 1,
          earlierParts: [],
          material: thisPart,
        };
        //if (existPart) {
        //  partQtyModalInfo.qty = existPart.qty;
        //}
        rackmatStore.showPartQtyModal(partQtyModalInfo);
      } else {
        moveStore.addShipMaterial(thisPart);
        rackmatStore.addScannedPart({
          rack_no: thisPart.rack_no,
          part_no: thisPart.part_no,
          qty: 1,
        });
      }
    }
  };
  const handleChooseScanQty = (scannedMaterial) => {
    moveStore.addMoveMaterial(scannedMaterial);
  };
  return (
    <>
      <ScrollView
        contentContainerStyle={
          isMovingEmpty ? styles.centerScrollContainer : undefined
        }>
        {isMovingEmpty && (
          <View style={styles.emptyMoveContainer}>
            <IconX origin="MaterialIcons" name="filter-none" size={48} />
            <Text>尚无可移架项,请扫码添加</Text>
          </View>
        )}
        <ScannedMaterialCard partItems={movingParts} />
      </ScrollView>
      <Modal
        visible={scanning}
        onClose={() => {
          setScanning(false);
        }}>
        <RackMaterialScanner
          onMaterialScan={handleMaterialScan}
          onChooseScannedMaterialQty={handleChooseScanQty}
          onExitScan={() => {
            setScanning(false);
          }}
        />
      </Modal>
      <Flex style={styles.hpadding5}>
        <Flex.Item style={styles.scanFlex}>
          <Button
            type={isMovingEmpty ? 'primary' : 'ghost'}
            key="scan"
            onPress={() => {
              setScanning(true);
            }}>
            <IconX name="scan" origin="ionicons" />
            扫件
          </Button>
        </Flex.Item>

        {!isMovingEmpty && (
          <Flex.Item style={styles.moveActionFlex}>
            <Button type="primary" key="submit">
              移架
            </Button>
          </Flex.Item>
        )}
      </Flex>
    </>
  );
}

AerialMaterialMovement.routeName = 'AerialMaterialMovement';
AerialMaterialMovement.permission = 'RMaterailMove';
export default AerialMaterialMovement;
